package es.udc.pfc.davidparedes.web.pages.user;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.PageRenderLinkSource;

import es.udc.pfc.davidparedes.model.store.Store;
import es.udc.pfc.davidparedes.model.taskservice.TaskService;
import es.udc.pfc.davidparedes.model.universe.Universe;
import es.udc.pfc.davidparedes.model.universemanager.UniverseManager;
import es.udc.pfc.davidparedes.model.userservice.UserService;
import es.udc.pfc.davidparedes.model.util.GlobalNames;
import es.udc.pfc.davidparedes.model.util.InstanceNotFoundException;

import es.udc.pfc.davidparedes.web.services.AuthenticationPolicy;
import es.udc.pfc.davidparedes.web.services.AuthenticationPolicyType;
import es.udc.pfc.davidparedes.web.util.UserSession;

@AuthenticationPolicy(AuthenticationPolicyType.DIRECTOR)
public class AddShift {
    
    @SessionState(create=false)
    private UserSession userSession;
    
    @Inject
    private UserService userService;
    
    @Inject
    private TaskService taskService;

    @Property
    private Date startDate;
    
    @Property
    private Date endDate;
    
    @Property
    private String startTime;
    
    @Property
    private String endTime;
    
    @Property
    private Boolean isRange;
    
    @Property
    private String permanent;
    
    @Property
    private List<String> permanentTypes;
    
    @Property
    private UniverseManager manager;
    
    @Property
    private List<UniverseManager> managers;
    
    @Component
    private Form addShiftForm;
    
    @Inject 
    private PageRenderLinkSource pageLinkSource;
    
    @Inject
    private Messages messages;
    
    
    void onActivate() {
    	try {
    		
    		Store store = userService.findUserProfile(userSession.getUserProfileId()).getStore();
    		
    		permanentTypes = new ArrayList<String>();
    		permanentTypes.add(Character.toString(GlobalNames.SHIFT_PERMANENT_NONE));
    		permanentTypes.add(Character.toString(GlobalNames.SHIFT_PERMANENT_MORNING));
    		permanentTypes.add(Character.toString(GlobalNames.SHIFT_PERMANENT_EVENING));
    		
    		managers = new ArrayList<UniverseManager>();
    		for (Universe universe : store.getUniverses()) {
    			if (universe.getManager() != null) {
    				managers.add(universe.getManager());
    			}
    		}
    		
			} catch (InstanceNotFoundException e) {
		}
    }

    Object onValidateFromAddShiftForm() {

        if (!addShiftForm.isValid()) {
            return this;
        }
        
        try {
			userService.findUniverseManager(manager.getUserProfileId());
        } catch (InstanceNotFoundException e1) {
			addShiftForm.recordError(messages.get("error-notFound"));
		}
        
        String[] shiftStartTime = startTime.split(":");
        Integer shiftStartHour = Integer.parseInt(shiftStartTime[0]);
        Integer shiftStartMin = Integer.parseInt(shiftStartTime[1]);
        Calendar shiftStart = Calendar.getInstance();
        shiftStart.setTime(startDate);
        if ((0 <= shiftStartHour) && (shiftStartHour <= 23) && (0 <= shiftStartMin) && (shiftStartMin <= 59)) {
        	shiftStart.set(Calendar.HOUR_OF_DAY, shiftStartHour);
        	shiftStart.set(Calendar.MINUTE, shiftStartMin);
        } else {
        	return this;
        }
        
        String[] shiftEndTime = endTime.split(":");
        Integer shiftEndHour = Integer.parseInt(shiftEndTime[0]);
        Integer shiftEndMin = Integer.parseInt(shiftEndTime[1]);
        Calendar shiftEnd = Calendar.getInstance();
        shiftEnd.setTime(endDate);
        if ((0 <= shiftEndHour) && (shiftEndHour <= 23) && (0 <= shiftEndMin) && (shiftEndMin <= 59)) {
	        shiftEnd.set(Calendar.HOUR_OF_DAY, shiftEndHour);
	        shiftEnd.set(Calendar.MINUTE, shiftEndMin);
        } else {
        	return this;
        }
        
        if (shiftStart.before(shiftEnd)) {
        	try {
        		
        		if (isRange) {
        			taskService.addShiftsRange(shiftStart, shiftEnd, (char) permanent.charAt(0), manager.getUserProfileId());
        		} else {
        			taskService.addShift(shiftStart, shiftEnd, (char) permanent.charAt(0), manager.getUserProfileId());
        		}
			} catch (InstanceNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        
        return StoreUMSchedule.class;
    }
    
    public ValueEncoder<UniverseManager> getUniverseManagerEncoder() {

        return new ValueEncoder<UniverseManager>() {

            @Override
            public String toClient(UniverseManager value) {
                return String.valueOf(value.getUserProfileId()); 
            }

            @Override
            public UniverseManager toValue(String id) { 
            	
            	UniverseManager manager = new UniverseManager();
                try {
					manager = userService.findUniverseManager(Long.parseLong(id));
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InstanceNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                
                return manager;
            }
        };
        
    }

}
